import re
import fire
import requests
from lxml import etree

headers = {
    'accept': "application/json"
}

prefix = ''


def tag_index():
    url = f"{prefix}/tags"
    resp = requests.request("GET", url)
    text = resp.text
    html = etree.HTML(text)
    return html


def get_tags(html) -> list:
    path = '/html/body/div[4]/div/main/div[2]/div/div[2]/div/div/div/div[1]/h4/a/text()'
    data = html.xpath(path)
    result = []
    for x in data:
        result.append(x.strip().replace('\n', ''))
    return result


def next_tag(tag):
    url = f'{prefix}/tags?after={tag}'
    resp = requests.request("GET", url)
    text = resp.text
    html = etree.HTML(text)
    path = '/html/body/div[4]/div/main/div[2]/div/div[3]/div/a[2]'
    data = html.xpath(path)
    if data:
        return html, True
    return html, False


def tag_json(tag):
    url = f'{prefix}/blob/{tag}/package.json'
    resp = requests.request("GET", url, headers=headers)
    text = resp.text
    split_text = re.split('devDependencies', text)
    text2 = split_text[-1]
    regex = r'<span class="pl-s"><span class="pl-pds">&quot;</span>webpack<span class="pl-pds">&quot;</span></span>: <span class="pl-s"><span class="pl-pds">&quot;</span>(.*)<span class="pl-pds">&quot;</span></span>'
    webpack = re.findall(regex, text2)
    regex2 = r'<span class="pl-s"><span class="pl-pds">&quot;</span>webpack-cli<span class="pl-pds">&quot;</span></span>: <span class="pl-s"><span class="pl-pds">&quot;</span>(.*)<span class="pl-pds">&quot;</span></span>'
    webpack_cli = re.findall(regex2, text2)
    return webpack, webpack_cli


def tags_json(tags, webpack_version):
    result = ''
    for tag in tags:
        webpack, webpack_cli = tag_json(tag)
        if webpack:
            version = webpack[0].split('^')[1]
            if str(webpack_version) >= version:
                result = tag
    return result


def all_tags(webpack_version):
    tag_list = []
    html = tag_index()
    tags = get_tags(html)
    tag_list.extend(tags)
    last_tag = tags[-1]
    tag = tags_json(tags, webpack_version)
    if tag:
        return tag
    while True:
        html2, flag = next_tag(last_tag)
        if flag:
            tags = get_tags(html2)
            tag_list.extend(tags)
            last_tag = tags[-1]
            tag = tags_json(tags, webpack_version)
            if tag:
                break
            continue
        tags = get_tags(html2)
        tag_list.extend(tags)
        tag = tags_json(tags, webpack_version)
        if tag:
            break
        break
    return tag


def run(pre, v):
    global prefix
    prefix = pre
    tag = all_tags(v)
    print(tag)


if __name__ == '__main__':
    fire.Fire()
